<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { Search, Refresh, Pointer, Tickets } from "@element-plus/icons-vue"
import { type FormInstance, ElMessage } from "element-plus"
import { formatDateTime } from "@/utils/index"
import { usePagination } from "@/hooks/usePagination"
import { shortcuts } from "@/utils/dateSet"
import useClipboard from "vue-clipboard3"
import { createLinkApi, getLinkApi } from "@/api/Shortlink/index"
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  time: "",
  shortLink: "",
  name: ""
})
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion

// #region 查找团队 团队持久
import { useTeamStore } from "@/store/modules/team"
const TeamListArr = ref()
const teamStore = useTeamStore()
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    TeamListArr.value = newValue.flat()
  },
  {
    immediate: true
  }
)
// #endregion

//  #region 查看所有信息
const tableData = ref<any>([])
const getTableData = async () => {
  if (!searchData.time) {
    searchData.time = []
  }
  await getLinkApi({
    start: new Date(searchData.time[0]).getTime() || "",
    end: new Date(searchData.time[1]).getTime() || "",
    size: paginationData.pageSize,
    page: paginationData.currentPage,
    shortLink: searchData.shortLink || "",
    name: searchData.name || ""
  }).then((res: any) => {
    tableData.value = res.data.list
    paginationData.total = res.data.total
    console.log(res, "获取")
  })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// #endregion

const dialogVisibleShortlink = ref(false) // 打开锻炼框
const formData = reactive<any>({ data: {} })
const currentUpdateId = ref<undefined | string>(undefined)
const formRef = ref<FormInstance | null>(null)
// 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
  copylink.value = ""
}
const resetForm = () => {
  getTableData()
  currentUpdateId.value = undefined
  formData.data = {}
  clearValidate()
}
// 打开短链生成弹窗
const ShortlinkCreate = () => {
  dialogVisibleShortlink.value = true
}
// 短链转换按钮
const copylink = ref("") // 复制的短链接
const convertTo = async () => {
  if (currentUpdateId.value == undefined) {
    await createLinkApi(formData.data).then((res: any) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg)
        copylink.value = res.data.shortLinkUrl
      } else {
        ElMessage.error("短链生成失败")
      }
    })
  } else {
    dialogVisibleShortlink.value = false
  }
}

const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制链接！")
  } catch (e) {
    ElMessage.error("没有生成短链接")
  }
}
</script>

<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="time" label="创建时间">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item label="短链名称" prop="name">
          <el-input v-model="searchData.name" placeholder="请输入短链名称" />
        </el-form-item>
        <el-form-item label="短链" prop="shortLink">
          <el-input v-model="searchData.shortLink" placeholder="请输入短链" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <div style="margin-left: 12px">
            <el-button type="primary" :icon="Pointer" @click="ShortlinkCreate">短链转换</el-button>
            <el-tooltip class="box-item" effect="dark" placement="bottom-start">
              <template #content
                >将长的URL网址,转换为简短的网址字符串<br />短链接可节省字符数空间,输入更多的短信内容</template
              >
              <el-icon size="20" color="#44a0ef"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 渲染 -->
    <el-card shadow="never">
      <div class="table-wrapper">
        <el-table :data="tableData" ref="tableRef">
          <el-table-column label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="短链名称" align="center" />
          <el-table-column prop="shortLink" label="短链接" align="center" />
          <el-table-column prop="originalUrl" label="长链接" />
          <!-- <el-table-column prop="type" label="链接打开次数" />
          <el-table-column prop="type" label="短链可用状态" /> -->
          <!-- <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">查看详情</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 查看/修改 -->
    <el-dialog
      v-model="dialogVisibleShortlink"
      :title="currentUpdateId === undefined ? '短链转换' : '查看'"
      @close="resetForm"
      width="40%"
    >
      <el-form ref="formRef" :model="formData.data" label-width="100px" label-position="left">
        <el-form-item label="短链名称" prop="name">
          <el-input v-model="formData.data.name" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="长网址链接" prop="originalUrl">
          <el-input v-model="formData.data.originalUrl" placeholder="请输入长链接" class="input-with-select">
            <template #append>
              <el-button :icon="Refresh" @click="convertTo">转换</el-button>
            </template>
          </el-input>
        </el-form-item>
        <div>
          <el-text class="mx-1" type="info">我们可以帮您把长链接压缩,让您可以输入更多的内容。</el-text>
          <br />
          <el-text class="mx-1" type="info"
            >插入短信内容中时,将在链接前后生成空格符号,以防止出现手机短信客户端不识别链接的情况。</el-text
          >
        </div>
        <br />
        <el-form-item label="短网址链接" prop="dis">
          <el-input v-model="copylink" class="input-with-select" disabled>
            <template #append>
              <el-button :icon="Tickets" @click="copy(copylink)">复制</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisibleShortlink = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
